/*global define, console, session */
define([
    "dojo/request", 
    "dojo/promise/all",
    "thekla-search/SearchTable",
    "thekla-search/compressor/string",
    "thekla-search/compressor/date",
    "thekla-search/compressor/number",
    "lbg/coordinates",
    "dojo/dom",    
    "dijit/registry",
    "dojo/store/JsonRest",
    "dojox/form/Manager",
    "dijit/form/TextBox",
    "dijit/Dialog",
    "dijit/form/CheckBox",
    "dijit/form/SimpleTextarea"
], function (request, all, searchtable, string, date, number, coordinates, dom, registry, Rest) {
    return function () {
        
        var cube, resultColumns, dataColumns, link, coords, showNavData, notes,
            showNotes, noteForm, submitData, notesStore, actualRow,
            boxes, found;
        
        notes = function (event) {
            return "<img src='images/green-03.png'></img>";    
        };
        
        showNotes = function (event) {
            var row;
            row = cube.resultTable.row(event);            
            registry.byId("editNotesDialog").show();
            notesStore.query({
                user_id: session.user_id,
                box_id: row.data.topic 
            }).then(function (item) {
                actualRow = item[0] || {
                    note_text: "",
                    found: false
                };
                actualRow.found = (actualRow.found === "1");
                actualRow.box_id = row.data.topic;
                noteForm.setFormValues(actualRow);
            });
        };
        
        showNavData = function (event) {
            var row, lo, lat, form;
            row = cube.resultTable.row(event);
            if (row.data.longitude) {
                form = registry.byId("navDataForm");
                lo = coordinates.convertD(row.data.longitude);
                lat = coordinates.convertD(row.data.latitude);
                form.setFormValues({
                    data1: lo.d + " / " + lat.d,
                    data2: lo.dm + " / " + lat.dm,
                    data3: lo.dms + " / " + lat.dms
                });
                dom.byId("mapsLink").innerHTML = "<a target='_blank' href='https://maps.google.com/maps?q=" + lo.d + "," + lat.d + "'>" + row.data.starting_point + "</a>";
                registry.byId("navDataDialog").show();

            }
        };
        
        link = function (item, row) {
            return "<a target='_blank' href='http://www.letterboxing-germany.info/lbg_forum/viewtopic.php?t=" + item + "'>Forum</a>";
        };   
        
        coords = function (item, row) {
            if (row.longitude !== "---") {
                return "<img src='images/green-28.png'></img>";
            } else {
                return "";
            }
        };
        
        submitData = function (event) {
            event.preventDefault();
            event.stopPropagation(); 
            var values, newRow, isNew;
            
            if (!actualRow.id) {
                isNew = true;
            } else {
                isNew = false;
            }
            
            values = noteForm.gatherFormValues();
            actualRow.user_id   = session.user_id;
            actualRow.found     = values.found ? "1": "0";
            actualRow.note_text = values.note_text;
            
            if (isNew) {
                notesStore.add(actualRow);
            } else {
                notesStore.put(actualRow);
            }
            registry.byId("editNotesDialog").hide();
        };
    
        resultColumns = [
            {label: "Name",          field: "name"},
            {label: "Placer",        field: "placer_name"},
            {label: "KFZ",           field: "license_tag"},
            {label: "PLZ",           field: "postal_code"},
            {label: "Stadt",         field: "city"},
            {label: "Schwierigkeit", field: "puzzle"},
            {label: "Gelände",       field: "terrain"},
            {label: "Dauer",         field: "duration"},
            {label: "Länge",         field: "length"},
            {label: "Forum",         field: "topic", formatter: link},
            {label: "Notizen",       field: "notes", formatter: notes},
            {label: "Koord",         field: "coords", formatter: coords}
        ];   
    
        dataColumns = {
            name:        {label: "Name",   compressor: string()},
            placer_name: {label: "Placer", compressor: string()},
            license_tag: {label: "KFZ",    compressor: string()},
            postal_code: {label: "PLZ",    compressor: string()},
            city:        {label: "Stadt",  compressor: string()},
            puzzle:      {label: "Schwierigkeit"},
            terrain:     {label: "Gelände"},
            duration:    {label: "Dauer"},
            length:      {label: "Länge", compressor: number()},
            country:     {label: "Land"},
            province:    {label: "Bundesland"},
            place_date:  {label: "veröffentlicht", compressor: date()}
        };
        
        /* lokal server: "/letterbo_admin/lbg_list/"      */
        /* lokale liste: "../lbg/scripts/lbg/boxes.json"  */
        
        notesStore = new Rest({
            target: "db/admin/user_boxes/"
        });
        
        boxes = request("../lbg/scripts/lbg/boxes.json", {
            handleAs: "json"
        });
        
        found = notesStore.query({
            user_id: session.user_id
        });
        
        all([boxes, found]).then(function (data) {
                var boxes = data[0],
                    found = data[1];
                cube = searchtable(boxes, "container", {
                    resultTable: resultColumns,
                    dataTable: dataColumns
                });
                cube.resultTable.on(".field-coords:click", showNavData);
                cube.resultTable.on(".field-notes:click", showNotes);
                
            }, function (error) {
                console.log("An error occurred: " + error);
            }
        );
        
        // =========================================================================
        // Connect all GUI elements to the correct handlers
        // =========================================================================
        
        noteForm = registry.byId("noteForm");
        noteForm.on("submit", submitData);        
        
    };        
});
